from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime

from ..config import get_db
from ..models import User, ChatRoom, ChatMessage
from ..schemas.chat import ChatMessageRequest, ChatMessageResponse, ChatRoomBase, ChatRoomResponse
from .auth import get_current_user

router = APIRouter()


@router.post("/rooms", response_model=ChatRoomResponse)
def create_chat_room(room_data: ChatRoomBase, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """创建新的聊天室"""
    # 创建聊天室
    db_room = ChatRoom(
        name=room_data.name,
        description=room_data.description
    )
    
    # 添加创建者为成员
    db_room.members.append(current_user)
    
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    
    return db_room


@router.get("/rooms", response_model=List[ChatRoomResponse])
def get_chat_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """获取当前用户的所有聊天室"""
    rooms = current_user.chat_rooms
    
    # 添加成员数量信息
    for room in rooms:
        room.member_count = len(room.members)
    
    return rooms


@router.post("/messages", response_model=ChatMessageResponse)
def send_message(message_data: ChatMessageRequest, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """发送消息到聊天室"""
    # 检查聊天室是否存在
    room = db.query(ChatRoom).filter(ChatRoom.id == message_data.chat_room_id).first()
    if not room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat room not found"
        )
    
    # 检查用户是否是聊天室成员
    if current_user not in room.members:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You are not a member of this chat room"
        )
    
    # 创建消息
    db_message = ChatMessage(
        content=message_data.content,
        sender_type="user",  # 用户发送的消息
        chat_room_id=message_data.chat_room_id
    )
    
    db.add(db_message)
    db.commit()
    db.refresh(db_message)
    
    return db_message


@router.get("/messages/{chat_room_id}", response_model=List[ChatMessageResponse])
def get_messages(chat_room_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """获取聊天室的消息历史"""
    # 检查聊天室是否存在
    room = db.query(ChatRoom).filter(ChatRoom.id == chat_room_id).first()
    if not room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat room not found"
        )
    
    # 检查用户是否是聊天室成员
    if current_user not in room.members:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You are not a member of this chat room"
        )
    
    # 获取消息，按时间倒序排列
    messages = db.query(ChatMessage).filter(
        ChatMessage.chat_room_id == chat_room_id
    ).order_by(ChatMessage.created_at.desc()).offset(skip).limit(limit).all()
    
    # 反转列表，使消息按时间正序排列
    messages.reverse()
    
    return messages